package com.boyaa.lxc.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.util.Log;

public class PCPU {
	private static int totalCPUtime1 = 0;
	private static int totalCPUtime2 = 0;
	private static int idle1 = 0;
	private static int idle2 = 0;
	private static int [] cputime = new int[9]; 
	
	
	public static void pcpu(){
		String cpu = getCPUinfo();
		int total=0;
		int idle=0;
		int pcpu=0;
		if(cpu == null)
			return;
		String [] cpus = cpu.split(" +");
		if(cpus == null || cpus.length < 10)
			return ;
		for(int i=1;i<10;i++){
			cputime[i-1]=Integer.parseInt(cpus[i]);
			total += cputime[i-1];
		}
		if(total <= totalCPUtime1 || cputime[3] < idle1)
			return;
		totalCPUtime2 = total;
		idle2 = cputime[3];
		total = totalCPUtime2 - totalCPUtime1;
		idle = idle2 - idle1;
		totalCPUtime1 = totalCPUtime2;
		idle1 = idle2;
		
		pcpu = 100*(total-idle)/total;
		Log.d("PCPU","pcpu="+pcpu);
	}
	
    public static String getCPUinfo(){
    	String cpu = null;
    	ProcessBuilder cmd;
    	String [] args = {"/system/bin/cat","proc/stat"};
    	cmd = new ProcessBuilder(args);
    	InputStream in = null;
    	try {
			Process process = cmd.start();
			in = process.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			cpu = br.readLine();
			if(in != null){
				in.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    	return cpu;
    }
}
